import md5 from 'js-md5'
import { LocationQuery } from 'vue-router'

const objKeySort = (obj: LocationQuery): any => {
  //排序的函数
  const newkey = Object.keys(obj).sort() //先用Object内置类的keys方法获取要排序对象的属性名，再利用Array原型上的sort方法对获取的属性名进行排序，newkey是一个数组
  const newObj = {} as any //创建一个新的对象，用于存放排好序的键值对
  for (let i = 0; i < newkey.length; i++) {
    //遍历newkey数组
    if (Array.isArray(obj[newkey[i]])) {
      obj[newkey[i]] = (obj[newkey[i]] as Array<any>).sort()
    }
    newObj[newkey[i]] = obj[newkey[i]] //向新创建的对象中按照排好的顺序依次增加键值对
  }
  return newObj //返回排好序的新对象
}
const computeKey = (tab: string, attrs: LocationQuery): string => {
  const newAttrs = objKeySort(attrs)
  return tab + ':' + md5(JSON.stringify(newAttrs))
}

const TabsUtils = {
  addPane: (
    path: string,
    tab: string,
    tabName: string,
    attrs: LocationQuery
  ) => {
    const newKey = computeKey(tab, attrs)
    window.$store.commit('addPane', {
      path: path,
      name: newKey,
      tab: tab,
      tabName: tabName,
      attrs: attrs
    })
  }
}

export default TabsUtils
